package com.scau402.system.service.impl;

import java.util.*;

import com.scau402.common.annotation.DataScope;
import com.scau402.common.core.domain.AjaxResult;
import com.scau402.common.utils.*;
import com.scau402.system.domain.FeatureCache;
import com.scau402.system.domain.WmsJadeImage;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.scau402.system.mapper.WmsJadeFeatureMapper;
import com.scau402.system.domain.WmsJadeFeature;
import com.scau402.system.service.IWmsJadeFeatureService;

/**
 * 翡翠特征管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-07-17
 */
@Service
public class WmsJadeFeatureServiceImpl implements IWmsJadeFeatureService 
{
    @Autowired
    private WmsJadeFeatureMapper wmsJadeFeatureMapper;

    /**
     * 查询翡翠特征管理
     * 
     * @param id 翡翠特征管理主键
     * @return 翡翠特征管理
     */
    @Override
    public WmsJadeFeature selectWmsJadeFeatureById(Long id)
    {
        return wmsJadeFeatureMapper.selectWmsJadeFeatureById(id);
    }

    /**
     * 查询翡翠特征管理列表
     * 
     * @param wmsJadeFeature 翡翠特征管理
     * @return 翡翠特征管理
     */
    @Override
    @DataScope(tenantAlias = "t", userAlias = "u")
    public List<WmsJadeFeature> selectWmsJadeFeatureList(WmsJadeFeature wmsJadeFeature)
    {
//        wmsJadeFeature.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        return wmsJadeFeatureMapper.selectWmsJadeFeatureList(wmsJadeFeature);
    }

    /**
     * 新增翡翠特征管理
     * 
     * @param wmsJadeFeature 翡翠特征管理
     * @return 结果
     */
    @Override
    @DataScope(tenantAlias = "t", userAlias = "u")
    public int insertWmsJadeFeature(WmsJadeFeature wmsJadeFeature)
    {
        wmsJadeFeature.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        wmsJadeFeature.setCreateTime(DateUtils.getNowDate());
        wmsJadeFeature.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        return wmsJadeFeatureMapper.insertWmsJadeFeature(wmsJadeFeature);
    }

    /**
     * 修改翡翠特征管理
     * 
     * @param wmsJadeFeature 翡翠特征管理
     * @return 结果
     */
    @Override
    @DataScope(tenantAlias = "t", userAlias = "u")
    public int updateWmsJadeFeature(WmsJadeFeature wmsJadeFeature)
    {
        wmsJadeFeature.setUpdateTime(DateUtils.getNowDate());
        wmsJadeFeature.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        return wmsJadeFeatureMapper.updateWmsJadeFeature(wmsJadeFeature);
    }

    /**
     * 批量删除翡翠特征管理
     * 
     * @param ids 需要删除的翡翠特征管理主键
     * @return 结果
     */
    @Override
    public int deleteWmsJadeFeatureByIds(Long[] ids)
    {
        return wmsJadeFeatureMapper.deleteWmsJadeFeatureByIds(ids);
    }

    /**
     * 删除翡翠特征管理信息
     * 
     * @param id 翡翠特征管理主键
     * @return 结果
     */
    @Override
    public int deleteWmsJadeFeatureById(Long id)
    {
        return wmsJadeFeatureMapper.deleteWmsJadeFeatureById(id);
    }

    @Override
    public List<String> getJadeFeatures() {
        return wmsJadeFeatureMapper.getJadeFeatures();
    }

    @Override
    public List<Long> match_jade(WmsJadeFeature wmsJadeFeature, List<Long> list) {

        Long source_id = wmsJadeFeature.getImageId();
        String source_feature = wmsJadeFeature.getFeature();
        double[] source_feature_double = StringUtils.str2arr(source_feature);

        EuclideanDistanceCalculator calculator = new EuclideanDistanceCalculator();

        Map<Long, Double> features = new HashMap<>();

        CustomRedisConfig cc = new CustomRedisConfig();
        RedisURI redisUri = RedisURI.Builder.redis(cc.REDIS_HOST, cc.REDIS_PORT).withPassword(cc.AUTH).withDatabase(2).build();
        RedisClient client = RedisClient.create(redisUri);
        // 创建StatefulRedisConnection对象
        StatefulRedisConnection<String, String> connection = client.connect();
        // 获取同步的RedisCommands对象
        RedisCommands<String, String> commands = connection.sync();

//        loadRedisFeature(list, commands);

        for(int i=0; i<list.size(); i++) {
            // 排除检测的图像
            if(!(source_id.longValue()==list.get(i).longValue())) {
                double[] stock_feature_temp = getFeature(list.get(i).toString(), commands).getFeature();
                features.put(list.get(i), calculator.calculate(source_feature_double, stock_feature_temp));
            }
        }
        List<Map.Entry<Long, Double>> match_result = new ArrayList<>(features.entrySet());

        Collections.sort(match_result, new Comparator<Map.Entry<Long, Double>>() {
            @Override
            public int compare(Map.Entry<Long, Double> o1, Map.Entry<Long, Double> o2) {
                // 按照值的升序进行排序
                return Double.compare(o1.getValue(), o2.getValue());
            }
        });

        // 将排序后的 List 转换回 LinkedHashMap
        Map<Long, Double> sortedMap = new LinkedHashMap<>();
        for (Map.Entry<Long, Double> entry : match_result) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        List<Long> result = new ArrayList<>();
        for (Map.Entry<Long, Double> entry : sortedMap.entrySet()) {
            result.add(entry.getKey());
        }

        connection.close();
        client.shutdown();
        return result.subList(0,1);
    }

    // @Cacheable(value = "Features", key = "#rkey")
    public FeatureCache getFeature(String rkey, RedisCommands<String, String> commands) {
        FeatureCache fc = new FeatureCache();
        double[] stock_feature_temp = StringUtils.str2arr(commands.get(rkey));
        fc.setFeature(stock_feature_temp);
        return fc;
    }

    public void loadRedisFeature(List<Long> list, RedisCommands<String, String> commands) {
        for(int i=0; i<list.size(); i++) {
            Long imageId = list.get(i);
            if(commands.exists(imageId.toString()) == 0l) {
                String feature = selectWmsJadeFeatureByImageId(imageId).getFeature();
                commands.set(imageId.toString(), feature);
            } else {
                String feature = commands.get(imageId.toString());
            }
        }
    }



    @Override
    public WmsJadeFeature selectWmsJadeFeatureByImageId(Long source_image_id) {
        return wmsJadeFeatureMapper.selectWmsJadeFeatureByImageId(source_image_id);
    }

    @Override
    public int checkImageIdUnique(Long new_image_id) {
        return wmsJadeFeatureMapper.checkImageIdUnique(new_image_id);
    }

    @Override
    public List<Long> selectWmsJadeFeatureImageIdList(WmsJadeFeature wmsJadeFeature) {
        return wmsJadeFeatureMapper.selectWmsJadeFeatureImageIdList(wmsJadeFeature);
    }

    @Override
    public List<Long> selectInstockWmsJadeFeatureImageIdList(Long tenant_id) {
        return wmsJadeFeatureMapper.selectInstockWmsJadeFeatureImageIdList(tenant_id);
    }

    @Override
    public void deleteWmsJadeFeatureByImageId(Long source_image_id) {
        wmsJadeFeatureMapper.deleteWmsJadeFeatureByImageId(source_image_id);
    }


}
